/*
 *  wbos - entry point of application
 *
 *  Copyright (C) 2011 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
 *
 *      This file is part of wbos.
 *
 *  wbos is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  wbos is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with wbos.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "peparser.h"

/**   Printing help in the console

    * @return void
*/
void PrintHelp(void)
{
    std::cout << "Usage: wbos FILE [Address] [Base Address] Calculate offset of BSOD in driver" << std::endl;
    std::cout << "       wbos --help \t\t\t  Displays this help and exit" << std::endl;
}

/**   Entry point of application

    * @return 0 in case of error, or image base of pe file
*/
int main(int argc, char *argv[])
{
	std::cout << "+ wbos (windows bsod offset search) version 1.0.0.1" << std::endl;
	std::cout << "+ Copyright Volodymyr M. Shcherbyna 2011, www.shcherbyna.com" << std::endl << std::endl;

    if (argc != 4)
    {
        PrintHelp();

        return 0;
    }

    CPEParser parser(argv[1]);
    long long nImageBase = parser.getImageBase();

    if (nImageBase != 0)
    {
        long long nStartAddress = 0;
        long long nEndAddress   = 0;

		std::stringstream ss, ss2;

		ss << std::hex << argv[2];
		ss >> nStartAddress;

		ss2 << std::hex << argv[3];
		ss2 >> nEndAddress;

        std::cout << "File: " << argv[1] << std::endl;
        std::cout << "Crash Address: 0x" << std::hex << nStartAddress << std::endl;
        std::cout << "Base Address: 0x" << std::hex << nEndAddress << std::endl;

        std::cout << "PE ImageBase: 0x" << std::hex << nImageBase << std::endl;

        nEndAddress -= nStartAddress;

        if (nEndAddress < 0)
        {
            nEndAddress *= -1;
        }

        nImageBase += nEndAddress;

        std::cout << "Ida Pro Offset: 0x" << nImageBase << std::endl;
    }
    else
    {
        std::cout << "Unable to obtain ImageBase from file " << argv[1] << std::endl;
    }

    return (int)nImageBase;
}